#include "List.h"

// 从文件加载数据
void List::loadData()
{
    ifstream userFile("user.txt",ios::out | ios::in);
    ifstream studentFile("student.txt",ios::out | ios::in);
    string username, password;
    // 从文件中读取用户信息并添加到用户列表
    while (userFile >> username >> password) {
        userList.push_back(user(username, password));
    }
    string name;
    int id;
    double score;
    // 从文件中读取学生信息并添加到学生列表
    while (studentFile >> name >> id >> score) {
        studentList.push_back(student(name, id, score));
    }
    userFile.close();
    studentFile.close();
}

// 将数据保存到文件
void List::saveData()
{
    ofstream userFile("user.txt",ios::out);
    ofstream studentFile("student.txt",ios::out);
    // 将用户列表中的信息写入文件
    for (auto it = userList.begin(); it != userList.end(); it++) 
    {
        userFile << "用户名:" << it->username << " 密码:" << it->password << endl;
    }
    // 将学生列表中的信息写入文件
    for (auto it = studentList.begin(); it != studentList.end(); it++) {
        studentFile << "姓名:" << it->name << " 学号:" << it->id << " 成绩:" << it->score << endl;
    }
    userFile.close();
    studentFile.close();
}

// 用户登录
bool List::login(string username, string password)
{
    for (auto it = userList.begin(); it != userList.end(); it++)
    {
        if (it->username == username && it->password == password)
        {
            return true;
        }
    }
    return false;
}

// 添加用户
void List::addUser(string username, string password)
{
    userList.push_back(user(username, password));
    cout << "添加用户成功" << endl;
}

// 删除用户
void List::deleteUser(string username)
{
    for (auto it = userList.begin(); it != userList.end(); it++)
    {
        if (it->username == username)
        {
            userList.erase(it);
            cout << "删除用户成功" << endl;
            break;
        }
    }
}

// 添加学生
void List::addStudent(string name, int id, double score)
{
    studentList.push_back(student(name, id, score));
    cout << "添加学生成功" << endl;
}

// 删除学生
void List::deleteStudent(int id)
{
    for (auto it = studentList.begin(); it != studentList.end(); it++)
    {
        if (it->id == id)
        {
            studentList.erase(it);
            cout << "删除学生成功" << endl;
            break;
        }
    }
}

// 查看学生成绩
void List::checkStudentScore(int id)
{
    for (auto it = studentList.begin(); it != studentList.end(); it++)
    {
        if (it->id == id)
        {
            cout << "姓名:" << it->name << " 学号:" << it->id << " 成绩:" << it->score << endl;
            return;
        }
    }
    cout << "未找到该学生" << endl;
}

// 修改学生成绩
void List::updateStudentScore(int id, double newScore)
{
    for (auto it = studentList.begin(); it != studentList.end(); it++)
    {
        if (it->id == id)
        {
            it->score = newScore;
            cout << "修改学生成绩成功" << endl;
            return;
        }
    }
    cout << "未找到该学生" << endl;
}